package date0704am;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 对于同一个 connection 来说，如果一个事务提交了，则意味着有一个新的事务随即开始了
 */
public class JdbcTest20 {

	public static void main(String[] args) throws Exception {

		String driverClassName = "oracle.jdbc.driver.OracleDriver";
		String url = "jdbc:oracle:thin:@localhost:1521:ecut";
		String user = "ecuter";
		String password = "ecuter";

//		String driverClassName = "com.mysql.cj.jdbc.Driver"  ;
//		String url = "jdbc:mysql://localhost:3306/ecut?serverTimezone=Asia/Shanghai&useSSL=false" ;
//		String user = "ecuter" ;
//		String password = "ecuter" ;

		// 1、加载数据库驱动
		Class.forName(driverClassName);
		// 2、获得数据库连接
		Connection connection = DriverManager.getConnection(url, user, password);
		
		connection.setTransactionIsolation( Connection.TRANSACTION_READ_COMMITTED ); 
		connection.setAutoCommit( false ); 
		
		System.out.println( "transaction isolation level : " + connection.getTransactionIsolation() ); // 2
		System.out.println( "autocommit : " + connection.getAutoCommit() ); // false
		
		Statement statement = connection.createStatement();
		
		try {
			String delete = "DELETE FROM t_users WHERE id = 1 " ;
			int count = statement.executeUpdate( delete ); 
			System.out.println( count );
			connection.commit(); // 提交事务 : 意味着当前会话中的一个事务终结，另一个事务立即开始
		} catch (SQLException e) {
			connection.rollback(); // 回滚事务
		}
		
		connection.setTransactionIsolation( Connection.TRANSACTION_SERIALIZABLE ); 
		
		System.out.println( "transaction isolation level : " + connection.getTransactionIsolation() ); // 8
		System.out.println( "autocommit : " + connection.getAutoCommit() ); // false
		
		Thread.sleep( 10000 );
		
		try {
			String delete = "DELETE FROM t_users WHERE id = 2 " ;
			int count = statement.executeUpdate( delete ); 
			System.out.println( count );
			connection.commit(); // 提交事务 : 意味着当前会话中的一个事务终结，另一个事务立即开始
		} catch (SQLException e) {
			connection.rollback(); // 回滚事务
		}
		

		// 6、释放资源( 所有已经开启的资源必须都关闭 )
		statement.close();
		connection.close();

	}

}
